<?php
declare (strict_types = 1);

namespace app\middleware;

use Exception;
use Firebase\JWT\JWT;
use Firebase\JWT\Key;
use think\cache\driver\Redis;
use think\facade\Cache;

class AdminAuth
{
    /**
     * 处理请求
     *
     * @param \think\Request $request
     * @param \Closure       $next
     * @return Response
     */
    public function handle($request, \Closure $next)
    {
        // todo 用JWT 解析 token, 获取 user id 
        // todo 查看 redis 中是否有token 数据
        $key = md5('字符串加密');
        $token = $request->param('token');
        if( !$token ){
            return json( [
                'code'=>1,
                'message'=>'没有权限',
            ] );
        }
        try{
            $jwtAuth = JWT::decode($token,new Key($key,'HS256'));
        }catch( Exception $e ){
            return json( [
                'code'=>1,
                'exception'=>$e->getMessage(),
                'message'=>'没有权限',
            ] );
        }

        $authInfo = json_decode(json_encode($jwtAuth), true);

        $redis = Cache::store('redis')->handler();

        // $redis_token = $redis->get('admin-token:' . $authInfo['user_id']);
        $redis_token = $redis->hget('admin::' . $authInfo['user_id'], 'token');
        if( $redis_token == $token ){
            $request->auth = $authInfo;
            return $next($request);
        }else{
            return json([ 'code'=>1, 'message'=>'没有权限' ]);
        }
        
    }
}
